<script setup lang="ts">
import { watch, shallowRef, ref } from 'vue'
import { NTag } from 'naive-ui'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'

interface Cre {
  id: string
  certificateNo: string
  certificateTypeName: string
}

const porps = defineProps<{
  batchId?: string | number | null
}>()

const cres = shallowRef<Cre[]>([])
const cresLoading = ref(false)

const queryCres = async () => {
  try {
    cresLoading.value = true
    const [error, res] = await sendRequest<HttpResponse<Cre[]>>({
      module: 'batchV2',
      api: 'cres',
      override: {
        params: {
          batchId: porps.batchId
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    cres.value = res.data
  } catch (error) {
    console.error(error)
  } finally {
    cresLoading.value = false
  }
}

watch(
  () => porps.batchId,
  (v) => {
    if (!v) return
    queryCres()
  },
  {
    immediate: true,
    flush: 'post'
  }
)
</script>

<template>
  <div class="batch-cres">
    <template v-if="cresLoading">
      <span>/</span>
    </template>

    <template v-else-if="cres.length === 0">
      <span style="color: #cccccc; font-size: 12px; line-height: 1">暂无证书</span>
    </template>

    <template v-else>
      <NTag
        v-for="item in cres"
        :key="item.id"
        :bordered="false"
        type="success"
        class="batch-cres__item"
        @click="
          $router.push({
            name: 'DonationCertificateDetail',
            params: { id: item.id },
            query: {
              redirect: $route.fullPath
            }
          })
        "
      >
        <span>{{ item.certificateTypeName }}</span>
      </NTag>
    </template>
  </div>
</template>

<style lang="scss" scoped>
.batch-cres {
  display: inline-flex;
  flex-wrap: wrap;
  gap: 5px;
  padding: 10px;
  background-color: rgb(250, 250, 252);
}

.batch-cres__item {
  cursor: pointer;
}

.batch-cres__item :deep(.n-tag__content) {
  display: inline-flex;
  align-items: center;
  justify-content: space-between;
  gap: 0 10px;
  flex: 1;
}
</style>
